<template>
  <div>
    <input v-model="message" type="text" placeholder="Type your message">
    <button @click="sendMessage">Send</button>
    <ul>
      <li v-for="msg in messages" :key="msg.id">
        <div class="message">
          <div class="user-info">
            <image :src="msg.message.head_image" alt="User Avatar" style="width: 50rpx;height: 50rpx;" />
            <span class="username">{{ msg.message.username }}</span>
          </div>
          <div class="message-content">
            <span class="time">{{ msg.message.timestamp }}</span>
            <p>{{ msg.message.message }}</p>
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
  import util from '@/libs/util'
  import {
    mapState,
    mapActions
  } from 'vuex'
  export default {
    data() {
      return {
        message: '',
        messages: []
      }
    },
    computed: {
      ...mapState('d2admin/user', [
        'info'
      ])
    },
    mounted() {
      const socket = new WebSocket('ws://localhost:8000/chat-channel/62/') // Replace with your server URL and room name
      socket.onopen = () => {
        console.log('WebSocket connection established.')
      }
      socket.onmessage = (event) => {
        const data = JSON.parse(event.data)
        this.messages.push(data)
      }
      socket.onclose = () => {
        console.log('WebSocket connection closed.')
      }
      this.username = this.info.userinfo.username
      this.user_id = this.info.userinfo.id // 用户id
      console.log('用户信息', this.info.userinfo);
      this.head_image = this.info.userinfo.head_image // 用户头像
    },
    methods: {
      sendMessage() {
        const socket = new WebSocket(
          'ws://localhost:8000/chat-channel/62/') // Replace with your server URL and room name
        const timestamp = new Date().toLocaleTimeString() // 获取当前时间
        socket.onopen = () => {
          const messageData = {
            message: this.message,
            username: this.username,
            user_id: this.user_id,
            head_image: this.head_image,
            timestamp: timestamp
          }
          socket.send(JSON.stringify(messageData))
          this.message = ''
        }
      }
    }
  }
</script>
